import type { Recordable } from '@vben/types';

import { h } from 'vue';

// 图标地址： https://icon-sets.iconify.design/
import { IconifyIcon } from '@vben/icons';
import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { get, isFunction } from '@vben/utils';

import { objectOmit } from '@vueuse/core';
import { ElButton, ElImage, ElPopconfirm, ElSwitch, ElTag } from 'element-plus';

import { DictTag } from '#/components/dict-tag';
import { $t } from '#/locales';

import { getIcon, getTitle, globalButtonConfig } from './button.config';
import { useVbenForm } from './form';

setupVbenVxeTable({
  configVxeTable: (vxeUI) => {
    vxeUI.setConfig({
      grid: {
        align: 'center',
        border: false,
        columnConfig: {
          resizable: true,
        },
        formConfig: {
          enabled: false,
        },
        minHeight: 180,
        proxyConfig: {
          autoLoad: true,
          response: {
            result: 'list',
            total: 'total',
            list: '',
          },
          showActiveMsg: true,
          showResponseMsg: false,
        },
        round: true,
        showOverflow: true,
        size: 'small',
      },
    });

    // 清理旧渲染器
    vxeUI.renderer.forEach((_, key) => {
      if (key.startsWith('Cell')) {
        vxeUI.renderer.delete(key);
      }
    });

    // 图片单元格
    vxeUI.renderer.add('CellImage', {
      renderTableDefault(_, params) {
        const { column, row } = params;
        return h(ElImage, {
          src: row[column.field],
          previewSrcList: [row[column.field]],
          hideOnClickModal: true,
          zIndex: 2000,
        });
      },
    });

    // 链接单元格
    vxeUI.renderer.add('CellLink', {
      renderTableDefault(renderOpts) {
        const { props } = renderOpts;
        return h(
          ElButton,
          {
            size: 'small',
            type: 'text',
            link: true,
            class: 'px-1',
          },
          { default: () => props?.text },
        );
      },
    });

    // 标签单元格
    vxeUI.renderer.add('CellTag', {
      renderTableDefault({ options, props }, { column, row }) {
        const value = get(row, column.field);
        const tagOptions = options ?? [
          { type: 'success', label: $t('common.enabled'), value: 1 },
          { type: 'danger', label: $t('common.disabled'), value: 0 },
        ];
        const tagItem = tagOptions.find((item) => item.value === value);
        return h(
          ElTag,
          {
            ...props,
            ...objectOmit(tagItem ?? {}, ['label']),
            type: tagItem?.type || 'info',
          },
          { default: () => tagItem?.label ?? value },
        );
      },
    });
    // 表格配置项可以用 cellRender: { name: 'CellDict', props:{dictType: ''} },
    vxeUI.renderer.add('CellDict', {
      renderTableDefault(renderOpts, params) {
        const { props } = renderOpts;
        const { column, row } = params;
        if (!props) {
          return '';
        }
        // 使用 DictTag 组件替代原来的实现
        return h(DictTag, {
          type: props.type,
          value: row[column.field]?.toString(),
        });
      },
    });
    // 开关单元格
    vxeUI.renderer.add('CellSwitch', {
      renderTableDefault({ attrs, props }, { column, row }) {
        const loadingKey = `__loading_${column.field}`;
        const finallyProps = {
          activeText: $t('common.enabled'),
          inactiveText: $t('common.disabled'),
          activeValue: 1,
          inactiveValue: 0,
          ...props,
          modelValue: row[column.field],
          loading: row[loadingKey] ?? false,
          style:
            'style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"',
          'onUpdate:modelValue': onChange,
        };

        async function onChange(newVal: any) {
          row[loadingKey] = true;
          try {
            const result = await attrs?.beforeChange?.(newVal, row);
            if (result !== false) {
              row[column.field] = newVal;
            }
          } finally {
            row[loadingKey] = false;
          }
        }

        return h(ElSwitch, finallyProps);
      },
    });

    // 操作列
    vxeUI.renderer.add('CellOperation', {
      renderTableDefault({ attrs, options, props }, { column, row }) {
        const defaultProps = {
          size: 'small',
          type: 'text',
          link: true,
          text: true,
          ...props,
        };
        const alignMap = {
          center: 'center',
          left: 'flex-start',
          right: 'flex-end',
          _fallback: 'flex-end',
        };
        const operations: Array<Recordable<any>> = (
          options || [
            {
              code: 'edit',
              type: 'primary',
            },
            {
              code: 'delete',
              type: 'danger',
            },
          ]
        )
          .map((opt) => {
            return { ...defaultProps, ...opt };
          })
          .map((opt) => {
            const optBtn: Recordable<any> = {};
            Object.keys(opt).forEach((key) => {
              optBtn[key] = isFunction(opt[key]) ? opt[key](row) : opt[key];
            });
            return optBtn;
          })
          .filter((opt) => opt.show !== false);

        // 合并配置的逻辑
        const mergeConfig = (opt: Recordable<any>) => {
          // 配置合并优先级：userOpt > 组件props > 全局默认
          return {
            ...globalButtonConfig.defaults,
            ...props,
            ...opt,
            // 特殊字段处理
            icon: undefined, // 始终禁用原生图标系统
            // 动态计算图标和文本
            _computedIcon: opt.icon ? opt.icon : getIcon(opt.code),
            _computedTitle: opt.title ? opt.title : getTitle(opt.code),
          };
        };

        function renderBtn(opt: Recordable<any>, listen = true) {
          const merged = mergeConfig(opt);

          return h(
            ElButton,
            {
              ...merged,
              // 清空按钮自带的 icon 属性（避免与插槽内容冲突）
              icon: undefined,
              onClick: listen
                ? () => attrs?.onClick?.({ code: merged.code, row })
                : undefined,
            },
            {
              default: () => [
                // 图标渲染
                h(IconifyIcon, {
                  icon: merged._computedIcon,
                  class: 'mr-1',
                  width: 14,
                  height: 14,
                }),
                // 文本渲染
                h('span', merged._computedTitle),
              ],
            },
          );
        }

        function renderConfirm(opt: Recordable<any>) {
          return h(
            ElPopconfirm,
            {
              title: $t('ui.actionTitle.delete', [attrs?.nameTitle || '']),
              confirmButtonText: $t('common.confirm'),
              cancelButtonText: $t('common.cancel'),
              onConfirm: () => {
                attrs?.onClick?.({ code: opt.code, row });
              },
            },
            {
              reference: () => renderBtn({ ...opt }, false),
            },
          );
        }

        const btns = operations.map((opt) =>
          opt.code === 'delete' ? renderBtn(opt) : renderBtn(opt),
        );

        return h(
          'div',
          {
            class: 'flex items-center gap-1',
            style: {
              justifyContent: column.align
                ? alignMap[column.align]
                : 'flex-end',
              width: '100%',
            },
          },
          btns,
        );
      },
    });
  },
  useVbenForm,
});

export { useVbenVxeGrid };
export type OnActionClickParams<T = Recordable<any>> = {
  code: string;
  row: T;
};
export type OnActionClickFn<T = Recordable<any>> = (
  params: OnActionClickParams<T>,
) => void;

export type * from '@vben/plugins/vxe-table';
